function rem(designWidth, maxWidth) {
	var doc = document,
	win = window,
	docEl = doc.documentElement,
	remStyle = document.createElement("style"),
	tid;

	function refreshRem() {
		var width = docEl.getBoundingClientRect().width;
		maxWidth = maxWidth || 540;
		width>maxWidth && (width=maxWidth);
		var rem = width * 100 / designWidth;
		remStyle.innerHTML = 'html{font-size:' + rem + 'px;}';
	}

	if (docEl.firstElementChild) {
		docEl.firstElementChild.appendChild(remStyle);
	} else {
		var wrap = doc.createElement("div");
		wrap.appendChild(remStyle);
		doc.write(wrap.innerHTML);
		wrap = null;
	}
	refreshRem();

	win.addEventListener("resize", function() {
		clearTimeout(tid);
		tid = setTimeout(refreshRem, 300);
	}, false);

	win.addEventListener("pageshow", function(e) {
		if (e.persisted) {
			clearTimeout(tid);
			tid = setTimeout(refreshRem, 300);
		}
	}, false);

	if (doc.readyState === "complete") {
		doc.body.style.fontSize = "16px";
	} else {
		doc.addEventListener("DOMContentLoaded", function(e) {
			doc.body.style.fontSize = "16px";
		}, false);
	}
	
	document.addEventListener('DOMContentLoaded', function() {
		FastClick.attach(document.body);
	}, false);
}
rem(750, 1024);

//项目部分
var api_init;
var baseUrl = "http://yimocai.keliren.com/api"  //接口地址 http://yimocai.keliren.com/doc.html
var sysColor = 'black';
function request(apis,params,callback,methods){
	console.log(apis+"参数：-----"+JSON.stringify(params))
	wx.showLoading();
	api.ajax({
		url: baseUrl+apis,
		method: methods || 'post',
		data: {
			values: params,
		}
	}, function(ret,err) {
		wx.hideLoading();
		err ? console.log(JSON.stringify(err)) : ''
		callback(err,ret);
	});
}
function upFile(src,callback){
	wx.showLoading();
	api.ajax({
		url: baseUrl + '/image',
		method: 'post',
		data: {
			files: {
				image: src
			}
		}
	}, function(ret, err) {
		wx.hideLoading();
		if (ret.code == 1) {
			callback(ret.data.image)
		} else {
			wx.showToast({title:"网络错误"})
		}
	});
}
apiready = function(){
	Vue.prototype.setData = function(obj){
		var _this = this;
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				_this[key] = obj[key];
			}
		}
	}
	/* 设置frame背景*/
	api.setStatusBarStyle({
		style: 'dark',
	});
	api.setWinAttr({
		bgColor: "#F8F9FB",
	});
	// Vue.config.silent = true;
	/*
	  vueComponent对象，可以通过调用  vueComponent.init()来加载所有组件
	  如果需要按需加载，在此处  vueComponent.allLoad = false;此时不需要调用init方法，
	                        在使用的页面主动调用vueComponent.load()；来加载所需组件
	*/
	typeof vueComponent == 'object' ? vueComponent.init()  : ""    //加载vue组件
	api_init == undefined ? ""  : api_init(); //初始化vue
	immersive();
	/**
	 * 页面公用跳转
	 * @param:添加节点class link-page
	 * @param:data-id    接收：api.pageParam.id;
	*/
	(function(){
		var linkPage = document.querySelectorAll('.link-page');
		for (var i = 0; i < linkPage.length;i++) {
			linkPage[i].addEventListener('click',function(){
				var paramString = this.dataset;
				var obj = {
					url:'',
					pageParam:{},
				};
				for (var key in paramString) {
					if (paramString.hasOwnProperty(key)) {
						key == "url" ? obj.url = paramString[key] : obj.pageParam[key] = paramString[key];
					}
				}
				api.openWin({
					name:obj.url,
					url:obj.url,
					pageParam:obj.pageParam,
				})
			},false)
		}
	})();
	/**
	 * 公用返回
	 * @param:添加公用类:back
	*/
	(function(){
		var backPage = document.querySelectorAll('.back');
		for (var i = 0; i < backPage.length;i++) {
			backPage[i].addEventListener('click',function(){
				api.closeWin();
			},true)
		}
	})();
}
// 沉浸式
function immersive(){
	if (api.statusBarAppearance) {
		var safeArea = api.safeArea.top;
		var safeArea_bottom = api.safeArea.bottom;
		var header = document.querySelector('.header');
		var main = document.querySelector('.main');
		var footer = document.querySelector('.footer')
		if(header != null){
			var headerHeight = header.clientHeight;
			header.style.height = headerHeight + safeArea + "px";
			$api.fixStatusBar(header);
		}
		if (main != null) {
			if (header) {
				var headerHeight = header.clientHeight;
			    main.style.paddingTop = headerHeight + "px";
			}else{
				main.style.paddingTop = safeArea + "px";
			}
		}
		if (footer != null) {
			var height2 = footer.clientHeight;
			footer.style.height = height2 + safeArea_bottom + "px";
			$api.fixTabBar(footer);
		}
	}
}
//下拉加载
function btLoad(_this,methods){
	var fn = methods || "getList";
	// 上拉加载
	var timp = "";
	api.addEventListener({
	　　name:'scrolltobottom',
		extra:{threshold:20}
	}, function(ret, err){
　　　　 //上拉加载时需要加载的数据
		if (_this.list.length == _this.total) {
			return false
		}else{
			clearTimeout(timp)
			timp = setTimeout(function(){
				_this[fn]();
			},300)
		}
	});
}
// 打开loading
var wx = {
	// 开启loading
	showLoading:function(){
		var UILoading = api.require('UILoading');
		UILoading.keyFrame({
		    rect: {
		        w: 120,
		        h: 120
		    },
		    styles: {
		        bg: 'rgba(0,0,0,0)',   
		        corner: 5,  
		        interval: 150,      
		        frame: {
		            w: 120,
		            h: 120 
		        }
		    },
		    mask:"rgba(255,255,255,0)",
		    content:[{ 
		     "frame":"widget://res/loading/1.png"
		    },{
		     "frame":"widget://res/loading/2.png"
		    },{
		     "frame":"widget://res/loading/3.png" 
		    },{
		     "frame":"widget://res/loading/4.png" 
		    },{
		     "frame":"widget://res/loading/5.png" 
		    },{
		     "frame":"widget://res/loading/6.png" 
		    },{ 
		     "frame":"widget://res/loading/7.png" 
		    },{
		     "frame":"widget://res/loading/8.png" 
		    },{
		     "frame":"widget://res/loading/9.png" 
		    },{
		     "frame":"widget://res/loading/10.png" 
		    },{
		     "frame":"widget://res/loading/11.png" 
		    },{
		     "frame":"widget://res/loading/12.png" 
		    }],
		}); 
	},
	//隐藏loading
	hideLoading:function(){
		var UILoading = api.require('UILoading');
		UILoading.closeKeyFrame();
	},
	/**
	 * 设置标题
	*/
	setNavigationBarTitle:function(params){
		if("title" in params){
			var title = params.title;
			var hd = document.querySelector('.header');
			var titleDomString = hd.querySelector('.middle').querySelector('span');
			titleDomString.innerHTML = title;
		}
	},
	showToast:function(params){
        if("title" in params){
			api.toast({msg:params.title})
		}
	},
	/**
	 * 路由跳转
	*/
	navigateTo:function(params){
		if('url' in params){
			var query = getBannerQuery(params.url);
			api.openWin({
				name:query.url + ".html",
				url:query.url + ".html",
				pageParam:query.params,
				reload:true,
			})
		}
	},
	/**
	 * 路由回退
	*/
	navigateBack:function(params){
		if(params && 'delta' in params){
			hisToWin(params.delta)
		}else{
			api.closeWin();
		}
	},
	/**
	 * 跳转tab层
	*/
	switchTab:function(params){
		if('url' in params){
			var jsfun = "api.setFrameGroupIndex({name:'root',index:"+params.url+"});";
			api.execScript({
				name: 'root',
				script: jsfun
			});
			api.closeToWin({
				name:"root"
			});
		}
	},
	/**重定向路由*/
	redirectTo:function(params){
		if('url' in params){
			api.addEventListener({
				name:'viewdisappear'
			},function(){
				api.closeWin();
			});
			var query = getBannerQuery(params.url);
			api.openWin({
				name:query.url + ".html",
				url:query.url + ".html",
				pageParam:query.params,
				reload:true,
			})
		}
	},
	/**
	 * 模态框
	 * @param {String} title 标题
	 * @param {String} content 内容
	 * @param {String} leftBtn 左按钮文案 
	 * @param {String} rightBtn 左按钮文案 
	 * @desc 依赖dialogbox模块   请勿使用取消按钮实现分之逻辑
	*/
	showModal:function(params){
		var dialogBox = api.require('dialogBox');
		params.title = params.title || '提示';
		params.leftBtn = params.leftBtn || '取消';
		params.rightBtn = params.rightBtn || '确定';
		params.icon = params.icon || 'widget://res/default_icon.png';
		dialogBox.alert({
			texts: {
				title: params.title,
				content: params.content,
				leftBtnTitle: params.leftBtn,
				rightBtnTitle: params.rightBtn
			},
			styles: {
				bg: '#fff',
				w: 300,
				corner:2,
				title: {
					marginT: 20,
					// icon: 'widget://res/lgout.png',
					icon:params.icon || "",
					iconSize: 32,
					titleSize: 18,
					titleColor: '#000'
				},
				content: {
					color: '#000',
					size: 14
				},
				left: {
					marginB:16,
					marginL: 20,
					w: 120,
					h: 35,
					corner: 2,
					bg: '#e5e5e5',
					color: '#fff',
					size: 14
				},
				right: {
					marginB:16,
					marginL: 20,
					w: 120,
					h: 35,
					corner: 2,
					bg: '#FB5C59',
					color: '#fff',
					size: 14
				}
			}
		}, function(ret,err) {
			dialogBox.close({
				dialogName: 'alert'
			});
			params.success ? 
			   params.success({confirm:ret.eventType == 'right',cancle:ret.eventType == 'left'}) :
			     ""
			
		});
	},
	//微信分享框
	share:function(callback){
		var dialogBox = api.require('dialogBox');
		dialogBox.actionMenu ({
			rect:{
				h: 150
			},
			items:[
			{
				text: '微信好友',
				icon: 'widget://image/weixin1.png'
			},
			{
				text: '朋友圈',
				icon: 'widget://image/weixin2.png'
			},
			],
			styles:{
				bg:'#FFF',
				column: 2,
				itemText: {
					color: '#000',
					size: 12,
					marginT:8
				},
				itemIcon:{
					size:60
				},
			},
			tapClose:true,
			animation:true,
		}, function(ret){
			dialogBox.close({
				dialogName: 'actionMenu'
			});
			if(ret.eventType == 'click'){
                callback(ret.index)
			}
		});
	}
}
//判断是否登录
function isLogin(){
	if(!$api.getStorage('userId')){
		api.openWin({
			name:"loginRole",
			url:api.wgtRootDir+"/html/login/login_rule.html",
		});
		return false
	}else{
		return true
	}
}
//读取当前用户的角色 //1 学生 2 老师 默认会返回学生
function getUserRole(){
	return $api.getStorage('userRole') || 1;
}
//判断是否是IOS
function isIos(){
	var systemType = api.systemType;
	return systemType == "ios";
}
//根据两个时间戳计算相差小时和天数（）@param1：当前时间 @param2：结束时间
function interval(faultDate,completeTime){
	var usedTime = completeTime - faultDate;  //两个时间戳相差的毫秒数
	if (usedTime < 0) {
		return {
			m:0,
			s:0,
		}
	}
	var m = Math.floor(usedTime%(60*60) / 60);
	var s = Math.floor(usedTime%(60*60) % 60);
	if (m < 10) {
		m = "0"+m
	}
	if (s < 10) {
		s = "0"+s
	}
	return{
		m:m,
		s:s,
	}
}
// 保存图片到本地
function savePicture(url){
	var timestamp = new Date().getTime()
	api.download({
		url: url,
		savePath: 'fs://test'+timestamp+'.jpeg',
		report: true,
		cache: true,
		allowResume: true
	}, function(ret, err) {
		if(ret){
			api.toast({
				msg:'图片已保存到本地'
			})
		}
		api.saveMediaToAlbum({
			path: 'fs://test'+timestamp+'.jpeg'
		}, function(ret, err) {

		});
	});
}
function ExitApp() {
	var ci = 0;
	var time1, time2;
	api.addEventListener({
	  name : 'keyback'
	}, function(ret, err) {
	  if (ci == 0) {
		time1 = new Date().getTime();
		ci = 1;
		api.toast({msg:'再按一次返回键退出'});
	  } else if (ci == 1) {
		time2 = new Date().getTime();
		if (time2 - time1 < 3000) {
		api.closeWidget({
		  id : api.appId,
		  retData : {
			name : 'closeWidget'
		  },
		  silent : true
		});
		} else {
		ci = 0;
		 api.toast({msg:'再按一次返回键退出'});
		}
	  }
	});
  }
  /*swiper*/
function swiper() {
	var swiper = new Swiper('.swiper-container', {
	 loop: true,
	 pagination: {
	  el: '.swiper-pagination',
	 },
	 autoplay: {
	  delay: 3000,
	  disableOnInteraction: false,
	 },
	 on: {
	   touchStart: function(event) {
		api.setFrameAttr({
		 name: api.frameName,
		 bounces: false
		});
	   },
	   touchEnd: function(event) {
		api.setFrameAttr({
		 name: api.frameName,
		 bounces: true
		});
	   },
		 }
	 });
}
//无数据
function isNoData(num){
	num == 0 ? document.querySelector('.no-data').style.display = 'block' : document.querySelector('.no-data').style.display = 'none';
}
// 动态加载JS
function loadJs(url, callback) {
	var script = document.createElement('script');
	script.type = "text/javascript";
	if (typeof (callback) != "undefined") {
		if (script.readyState) {
			script.onreadystatechange = function () {
				if (script.readyState == "loaded" || script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
				}
			}
		} else {
			script.onload = function () {
				callback();
			}
		}
	}
	script.src = url;
	document.body.appendChild(script);
}

//文本复制功能
function copy(text){
	//text为需要复制的文本
    var clipBoard = api.require('clipBoard');
	clipBoard.set({
   		value: text
	}, function(ret, err) {
    	if (ret) {
        	api.toast({msg:"复制成功",location:"middle"})
		} else {
    		api.toast({msg:"复制失败，请稍后重试",location:"middle"})
    	}
	});
}
/* 获取元素的css值 @param1：元素选择器。@param2：某个css的字符串， @param3:切除最后两位个数 50px => 50   */
function getEleCss(ele,cssMsg,iscut){
	var eleStyle,num;
	if (window.getComputedStyle) {
		eleStyle = window.getComputedStyle(ele,null);
		num = iscut ? eleStyle[cssMsg].substring(0,eleStyle[cssMsg].length-iscut) : eleStyle[cssMsg];
	} else {
		console.err('your brower is not support')
		num = "";
	}
	return num
}
// api回退页面
function hisToWin(num){
    if(!num){
		return false
	}
	var wins = api.windows();
	api.closeToWin({
		name:wins[wins.length- 1 - num].name,
	})
}
//无数据
function isNoData(num){
	if(document.querySelector('.no-data') == null){
        return false
	}
	num == 0 ? document.querySelector('.no-data').style.display = 'block' : document.querySelector('.no-data').style.display = 'none';
}
// 数组过滤空值
function filterAll(arr){
	var target = arr.filter(function(current){
		return current !== null && current !== undefined && current !== "";
	})
	target = target.map(function(v){
		v.goods = [];
		return v
	})
	return target;
}
//url参数解析
function getBannerQuery(url) {
	if (!url) {
	return false
	}
	var obj = {};
	var urlArr = url.split('?');
	obj.url = urlArr[0];
	if (urlArr.length == 2) {
		var param = urlArr[1].split('&');
		var xinObj = {};
		for (var i = 0; i < param.length; i++) {
			var eleArr = param[i].split('=');
			xinObj[eleArr[0]] = eleArr[1];
		};
		obj.params = xinObj;
	}
	return obj;
}
//数尾补两个0 1=>1.00 , 2.2=>2.20;
function setNum2(num){
	num += '';
	num = num.replace(/[^0-9|\.]/g, '');
	if(/^0+/){num = num.replace(/^0+/, '')}
	if(!/\./.test(num)){num += '.00'}
	if(/^\./.test(num)){num = '0' + num}
	num += '00';
	num = num.match(/\d+\.\d{2}/)[0];
	return num
}
//打电话
function callPhone(phone){
	wx.showModal({
		title:"拨打电话",
		content:"确定呼叫 "+phone+" 吗?",
		icon:"widget://res/call.png",
		rightBtn:"呼叫",
		success:function(res){
            if(res.confirm){
				api.call({
					type: 'tel_prompt',
					number: phone,
				});
		    }
		}
	})
}

/*计算缓存*/
function computedCash(size){
	var size = ~~(size / 1024); //kb
	if (size > 1024 ) {
			size = ~~(size / 1024) + "MB";
	} else {
			size = size + "KB";
	}
	return size;
}
//选择图片
function chosePic(callback){
	function getPic(t,callback){
		api.getPicture({
			sourceType: t,
			encodingType: 'jpg',
			mediaValue: 'pic',
			destinationType: 'url',
			allowEdit: true,
			quality: 50,
		}, function(ret, err) {
			if (ret) {
				if(ret.data != ""){
					data = ret.data;
					callback(data)
				}
			}else {
				api.toast({
					msg: '请重试'
				});
			}
		});
	}
	api.actionSheet({
		cancelTitle: '取消',
		buttons: ['拍照', '从相册选择'],
		style: {
			fontNormalColor: '#000',
		}
	}, function(ret, err) {
		var index = ret.buttonIndex;
		if (index == 1) {
			var resultList = api.hasPermission({
				list:['camera']
			});
			if(resultList[0].granted==true){
				getPic('camera',callback);
			}else{
				api.requestPermission({
					list:['camera'],
					code:1
				}, function(ret, err){
					if(ret.list[0].granted){
						getPic('camera',callback);
					}
				});
			}
		} else if (index == 2) {
			var resultList = api.hasPermission({
				list:['photos']
			});
			if(resultList[0].granted==true){
				getPic('photos',callback);
			}else{
				api.requestPermission({
					list:['photos'],
					code:1
				}, function(ret, err){
					if(ret.list[0].granted){
						getPic('photos',callback);
					}
				});
			}
		}
	});
}
/**
 * 1:note_delete  删除时传了数据字符串数组   提示请选择要删除的数据 最好更改数据传输格式 ，拼接
 * 2:learn_record_delete 删除时传了数据字符串数组   提示请选择要删除的数据 最好更改数据传输格式 ，拼接
*/

